package com.icode.web.startup.security;

import com.icode.core.dto.UserDTO;
import com.icode.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;

/**
 * User: alexz
 * Date: 2015/9/25
 * Time: 15:48
 */
@Configurable
public class MyAuthenticationToken extends UsernamePasswordAuthenticationToken {

    @Autowired
    private UserService userService;

    public MyAuthenticationToken(Object principal, Object credentials) {
        super(principal, credentials);
    }

    public MyAuthenticationToken(Object principal, Object credentials, Collection<? extends GrantedAuthority> authorities) {
        super(principal, credentials, authorities);
    }

    @Override
    public Collection<GrantedAuthority> getAuthorities() {
        String username = ((UserDTO) this.getPrincipal()).getUsername();
        Set<String> authorities = userService.loadAuthorities(username);
        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        for (String authority : authorities) {
            grantedAuthorities.add(new SimpleGrantedAuthority(authority));
        }
        return grantedAuthorities;
    }
}
